package com.hqq.behaviour.iterator;

import java.util.List;

/**
 * TreasureChestIterator
 * 具体迭代器角色
 * Created by heqianqian on 2017/6/17.
 */
public class TreasureChestIterator implements ItemIterator {

    private TreasureChest treasureChest;

    private ItemType itemType;

    private int idx;
    private int nextIdx;


    public TreasureChestIterator(TreasureChest treasureChest, ItemType itemType) {
        this.treasureChest = treasureChest;
        this.itemType = itemType;
        this.idx = -1;
    }

    @Override
    public boolean hasNext() {
        return getNextIdx() != -1;
    }

    @Override
    public Item next() {
        this.idx = getNextIdx();
        if (idx == -1) {
            return null;
        }
        return treasureChest.getItems().get(idx);
    }

    public int getNextIdx() {
        List<Item> items = treasureChest.getItems();
        int tempIdx = this.idx;
        while (true) {
            tempIdx++;
            if (tempIdx >= items.size()) {
                tempIdx = -1;
                break;
            } else if (itemType.equals(ItemType.ANY) || items.get(tempIdx).getItemType().equals(this.itemType)) {
                break;
            }
        }
        return tempIdx;
    }
}
